/**
 * Created by DELL on 2017/8/22.
 */
//命名空间
var deptinfores = {
    'name': '填写角色名称',
    'des': '填写角色描述',
    'deptArr': '',
    'deptModArr': '',
    'userArr': ''
}

/**
 *	@info 弹出组织架构窗口
 *	@author luoxt
 *	@date 2012-06-11
 */
var depchoice1 = '';
function getDeptWin(wrap,mode,id,uid,type,multiple,valide) {
    var _emp_show;
    if(type == 'emp'){
        _emp_show=1
    }else{
        _emp_show=0
    }
    depchoice1 = new depchoice({
        id:wrap?wrap:'groudtree',/*绑定的位置*/
        treeid:'d_tree',/*树绑定的位置*/
        /*数据源（local为本地生成好的json串格式，ajax为需要动态加载数据的方式，需要配合url使用,tree_JSON 构建树的内容,tree_JSON 只有在type为local时使用）*/
        datasource:{"type":"ajax","url":"http://119.23.232.192:8081/Organization/organize/organize_tree","tree_JSON":"","search_JSON":"","ajaxdata":[2],  "_emp_show":_emp_show},
        treeobj:'_tree',/*构建树的对象名称*/
        chkboxType:['ys','ns'],
        checked:multiple,
        mode:mode,/*有两种模式 简单(simple)和复杂(intricacy) 默认复杂模式(intricacy)*/
        sp:false,
        rs:function(val) {/*获得结果函数*/
            deptinfores.deptModArr = eval(val);
            console.log(deptinfores.deptModArr)
            //判断模式
            var _valide = valide?valide:''
            if(mode == 'intricacy'){
                fnHandlesimples(id,uid);
            }else if(mode == 'simple'){
                fnHandlesimple();
            }else if(mode == 'select' && multiple){
                
                fnHandleSelect(id,uid,type,_valide);
            }else if(mode == 'select' && !multiple){
                
                fnHandleSelectSingle(id,uid,type,_valide)
            }
        },
        fun:function(val){/*外部函数*/
            $('#mask').hide()
        }
    });
}
//$('#username4').on('change',function(){
//    showsDeptWin(obj,id,uid);
//})
/**
 *	@info 触发弹出组织架构窗口事件
 *	@author luoxt
 *	@date 2012-06-11
 */
function showsDeptWin(wrap,mode,id,uid,type,multiple,valide){
    //mode 模式 id 人员name  uid 人员id
    var object = $(this);
    var _multiple = false
    if(!arguments[5] || arguments[5] !== 'single'){
        _multiple = true
    }
    getDeptWin(wrap,mode,id,uid,type,_multiple,valide);
    depchoice1.display('show',function(){
        depchoice1.inputval = deptinfores.deptAddArr,oldUsers = $('#'+uid).val(),oldDepts = $('#depid').val();
        depchoice1.inputval = [];
        depchoice1.inputempval = [];
        if(oldUsers){
            var userArr = oldUsers.split(',');
            var userObject = $.map(userArr, function(id) {
                return {id: id, name: '' };
            });
            if(type == 'dep'){
                depchoice1.inputval = userObject;
            }else{
                depchoice1.inputempval = userObject;
            }
            
        }
        //console.log(oldUsers)
        //console.log(depchoice1.inputval,depchoice1.inputempval)
        /*人员组装格式 json串 [{"id":"12","name":"11"},{"id":"19","name":"11111"}] */
        // if(oldDepts){
        //     var deptArr = oldDepts.split(','),
        //         deptObject = $.map(deptArr, function(id) {
        //             return {id: id, name: '' };
        //         });
        //     depchoice1.inputval = deptObject;
        // }
        depchoice1.init();
    });
}


/**
 *	@info 触发弹出组织架构窗口事件
 *	@author luoxt
 *	@date 2012-06-11
 */
/*select模式 */
function fnHandleSelect(id,uid,type,valid){
    var jsonVal = deptinfores.deptModArr;
    var _id = '',_name = '',_arr=[]
    if(type == 'emp'){
        _arr = jsonVal[1]?jsonVal[1]:[]
    }else{
        _arr = jsonVal[0]?jsonVal[0]:[]
    }
    
    $.each(_arr,function(key,val){
        if(key < _arr.length-1){
            _id+= val['id']+',';
            _name+= val['name']+',';
        }else{
            _id+= val['id'];
            _name+= val['name'];
        }
    });
    console.log(_id)
    $("#"+uid).val(_id);
    if(valid){
        valid.check(false,$("#"+uid))
    }
    // $("#"+id).text(_name);
    tagSelected({data:_arr,elmName:id,delFn:function(elm,id,data){
        var _id=''
        _arr = _arr.filter(function(v){
            return v['id'] != id
        })
        $.each(_arr,function(key,val){
            
            if(key < _arr.length){
                _id+= val['id']+',';
            }else{
                _id+= val['id']
            }
        });
        $("#"+uid).val(_id);
    }})
}
function fnHandleSelectSingle(id,uid,type,valid){
    var jsonVal = deptinfores.deptModArr;
    var _id = '',_name = '',_arr=[]
    if(type == 'emp'){
        _arr = jsonVal[1]?jsonVal[1]:[]
    }else{
        _arr = jsonVal[0]?jsonVal[0]:[]
    }
    $.each(_arr,function(key,val){
        _id+= val['id'];
        _name+= val['name'];
    });
    $("#"+uid).val(_id);
    $("#"+id).val(_name)
    if(valid){
        valid.check(false,$("#"+uid))
    }
    // $("#"+id).text(_name);
    // tagSelected({data:_arr,elmName:id,delFn:function(elm,id,data){
    //     var _id=''
    //     _arr = _arr.filter(function(v){
    //         return v['id'] != id
    //     })
    //     $.each(_arr,function(key,val){
    //         _id+= val['id']+',';
    //     });
    //     $("#"+uid).val(_id);
    // }})
}
/* 删除按钮 */
function tagSelected(options){
    var _data = options.data,_html=''
    for(var i=0;i<_data.length;i++){
        _html += '<span class="circleX circle_grid"><em class="close_up">×</em><b class="circleGird" data-ids="'+_data[i].id+'">'+_data[i].name+'</b></span>'
    }
    $('#'+options.elmName).html(_html)
    $('.tagselect#'+options.elmName+' .circle_grid').off('click').on('click',function(){
        //depchoice1.display('none')
        if(options.gridFn){
            options.gridFn($(this))
        }
        $(document).click()
        return false;
    })
    $('.tagselect#'+options.elmName +' .circle_grid .close_up').off('click').on('click',function(elm){
        $(this).parent('span').remove()
        var _val=$(this).siblings('.circleGird').text()
        var _ids=$(this).siblings('.circleGird').data('ids')
        var _id = ''

        if(options.delFn){
            options.delFn($(this),_ids,_data)
        }
        $(document).click()
        return false;
    })
}
//回显赋值
function fnHandlesimple(){
    var jsonVal = deptinfores.deptModArr;
    deptArr = jsonVal[0];
    userArr = jsonVal[1];
    userid = '';
    deptid = '';
    username = '';
    deptname = '';

    $.each(deptArr,function(k,v){
        deptid= v['id'];
        deptname = v['name'];
    });

    $.each(userArr,function(key,val){
        userid= val['id'];
        username= val['name'];
    });

    if(userid == '' && deptid == ''){
        alert('请选择部门或人员查询!');
        return false;
    }

    if(deptname != ''){
        $('#checkuser').hide();
        $('#deptshowname').val(deptname);
        $('#checkdept').show();
    }else{
        $('#checkuser').hide();
        $('#deptshowname').val(username);
        $('#checkdept').show();
    }
}

//复杂模式回显
function fnHandlesimples1(id,uid){
    var jsonVal = deptinfores.deptModArr;

    userArr = jsonVal;
    var userid = '';
    var deptid = '';
    var username = '';
    var deptname = '';
    var showname = '';

//        $.each(deptArr,function(k,v){
//            deptid= v['id'];
//            deptname+= v['name'];
//        });

    $.each(userArr,function(key,val){
        userid+= val['id']+',';
        username+= val['name']+',';
    });

    $('#user_id').attr('value',userid);
//            $('#group_id').attr('value',deptid);


//        if(deptname != ''){
//            showname = deptname;
//        }else{
//    showname = username;
    //      }

    $("#"+uid).val(userid);
    $("#"+id).val(username);
}

//选择下拉列表 select2版
if(typeof rpSelect == "undefined"){
    if(typeof window.jQuery == "undefined"){
        throw('由于没有加载jQuery库，所以本功能不能使用，请加载jQuery库，谢谢合作！');
    }
    function rpSelect(_objs){
        var $sObj = this
        $sObj.args = $.extend({
            isId:false,
            sel:'',
            url:'',
            type:'POST',
            baseData:{sel:1},
            data:{},
            datas:[],
            multiple:true,
            placeholder:'请选择选项',
            valide:'',
            hasAll:false
        },_objs||{});
        $sObj.init = function(){
            var _data = $.extend({},$sObj.args.baseData,$sObj.args.data)
            if($sObj.args.datas.length != 0){
                setTimeout(function(){//延迟一下 vue数据更新时就不会出现无法使用的问题了
                    if($sObj.args.hasAll){
                        $sObj.args.datas.splice(0,0,{id:'none',text:'全部'})
                    }
                    $(($sObj.args.isId?'#':'.') + $sObj.args.sel).select2({
                        placeholder:$sObj.args.placeholder,
                        data:$sObj.args.datas,
                        multiple: $sObj.args.multiple,
                        closeOnSelect: !$sObj.args.multiple
                    })
                },0)
                
            }else{
                $.ajax({
                    url:$sObj.args.url,
                    type:$sObj.args.type,
                    data:_data,
                    dataType:"json",
                    success:function(res){
                        if(res.code == 0){
                            $sObj.args.datas = res.data
                            if($sObj.args.hasAll){
                                $sObj.args.datas.splice(0,0,{id:'none',text:'全部'})
                            }   
                        }
                        $(($sObj.args.isId?'#':'.') + $sObj.args.sel).select2({
                            placeholder:$sObj.args.placeholder,
                            data:$sObj.args.datas,
                            multiple: $sObj.args.multiple,
                            closeOnSelect: !$sObj.args.multiple
                        })
                        if($sObj.args.valide && $sObj.args.valide != ''){
                            $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:close", function (e) {
                                var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                            $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:select", function (e) {
                                var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                            $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:unselect", function (e) {
                                $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                        }
                        
                        
                    },
                    complete:function(res){
                        
                    },
                    error:function(res){
                        console.log(res)
                    }    
                })
            }
            // if($sObj.args.multiple){
            //     $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:select", function (e) {
            //         // $(($sObj.args.isId?'#':'.') + $sObj.args.sel).select2('open')
            //     });
            //     $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:close", function (e) {
                    
            //     });
            // }
        }
        $sObj.init()

    }
}
